<template>
	<view class="content">
		<view class="input-area">
			<input type="text" v-model="ipAddress" placeholder="请输入IP地址（可选）" class="ip-input" :disabled="isLoading" />
			<button @click="getLocation" class="search-btn" :disabled="isLoading">
				<text v-if="!isLoading">获取位置</text>
				<text v-else>查询中...</text>
			</button>
		</view>
		<view class="system-info">
			<view class="info-item">
				<text class="label">平台：</text>
				<text class="value">{{ systemInfo.platform }}</text>
			</view>
			<view class="info-item">
				<text class="label">系统：</text>
				<text class="value">{{ systemInfo.system }}</text>
			</view>
			<view class="info-item">
				<text class="label">版本：</text>
				<text class="value">{{ systemInfo.version }}</text>
			</view>
			<view class="info-item">
				<text class="label">品牌：</text>
				<text class="value">{{ systemInfo.brand }}</text>
			</view>
			<view class="info-item">
				<text class="label">语言：</text>
				<text class="value">{{ systemInfo.language }}</text>
			</view>
			<view class="info-item">
				<text class="label">网络类型：</text>
				<text class="value">{{ systemInfo.networkType }}</text>
			</view>
			<view class="info-item">
				<text class="label">当前时间：</text>
				<text class="value">{{ currentTime }}</text>
			</view>
		</view>
		<view class="history-toggle" @click="showHistory = !showHistory">
			<text>历史记录</text>
			<text class="toggle-icon">{{ showHistory ? '▼' : '▶' }}</text>
		</view>
		<view class="history-list" v-if="showHistory && historyList.length > 0">
			<view v-for="(item, index) in historyList" :key="index" class="history-item" @click="loadHistoryItem(item)">
				<text class="history-ip">{{ item.ip || '当前IP' }}</text>
				<text class="history-location">{{ item.province }} {{ item.city }}</text>
			</view>
		</view>
		<view class="result-area" v-if="locationInfo">
			<view class="info-item">
				<text class="label">省份：</text>
				<text class="value">{{ locationInfo.province }}</text>
			</view>
			<view class="info-item">
				<text class="label">城市：</text>
				<text class="value">{{ locationInfo.city }}</text>
			</view>
			<view class="info-item">
				<text class="label">区域编码：</text>
				<text class="value">{{ locationInfo.adcode }}</text>
			</view>
			<view class="info-item">
				<text class="label">经纬度范围：</text>
				<text class="value">{{ locationInfo.rectangle }}</text>
			</view>
		</view>
		<view class="copyright-area">
			<view class="copyright-card">
				<view class="copyright-item">
					<text class="copyright-label">作者：</text>
					<text class="copyright-value">坚果派</text>
				</view>
				<view class="copyright-item">
					<text class="copyright-label">公众号：</text>
					<text class="copyright-value">nutpi</text>
				</view>
				<view class="copyright-item">
					<text class="copyright-label">电话：</text>
					<text class="copyright-value">17752170152</text>
				</view>
				<view class="copyright-item">
					<text class="copyright-label">官网：</text>
					<text class="copyright-value">https://www.nutpi.net/</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			ipAddress: '',
			locationInfo: null,
			// API密钥从环境变量读取
			apiKey: import.meta.env.VITE_AMAP_API_KEY,
			isLoading: false,
			historyList: [],
			showHistory: false,
			systemInfo: {
				platform: '',
				system: '',
				version: '',
				brand: '',
				language: '',
				networkType: ''
			},
			currentTime: ''
		}
	},
	created() {
		this.initSystemInfo()
		this.startTimeUpdate()
		this.loadHistoryFromStorage()
	},
	methods: {
		initSystemInfo() {
			const info = uni.getSystemInfoSync()
			this.systemInfo = {
				platform: info.platform,
				system: info.system,
				version: info.version,
				brand: info.brand,
				language: info.language,
				networkType: info.networkType || '获取中...'
			}
			// 获取网络类型
			uni.getNetworkType({
				success: (res) => {
					this.systemInfo.networkType = res.networkType
				}
			})
		},
		startTimeUpdate() {
			const updateTime = () => {
				this.currentTime = new Date().toLocaleString()
			}
			updateTime()
			setInterval(updateTime, 1000)
		},
		loadHistoryFromStorage() {
			try {
				const history = uni.getStorageSync('ipLocationHistory')
				if (history) {
					this.historyList = history
				}
			} catch (e) {
				console.error('读取历史记录失败:', e)
			}
		},
		loadHistoryItem(item) {
			this.ipAddress = item.ip
			this.locationInfo = item
		},
		validateIP(ip) {
			if (!ip) return true; // 允许空值，使用当前IP
			const pattern = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
			return pattern.test(ip);
		},
		async getLocation() {
			const queryIP = this.ipAddress || '61.178.51.181';
			if (queryIP && !this.validateIP(queryIP)) {
				uni.showToast({
					title: 'IP地址格式不正确',
					icon: 'none'
				});
				return;
			}

			this.isLoading = true;
			try {
				console.log('开始获取位置信息', `IP地址: ${queryIP}`)
				const url = `https://restapi.amap.com/v3/ip?key=${this.apiKey}&ip=${queryIP}`
				console.log('请求URL:', url)

				const response = await uni.request({
					url: url,
					method: 'GET',
					timeout: 10000
				})
				console.log('API响应数据:', response.data)

				if (response.data.status === '1') {
					this.locationInfo = response.data
					// 保存到历史记录
					const historyItem = {
						ip: this.ipAddress,
						...response.data,
						timestamp: new Date().getTime()
					}
					this.historyList.unshift(historyItem)
					if (this.historyList.length > 10) {
						this.historyList.pop()
					}
					uni.setStorageSync('ipLocationHistory', this.historyList)
					console.log('位置信息获取成功:', {
						省份: response.data.province,
						城市: response.data.city,
						区域编码: response.data.adcode,
						经纬度范围: response.data.rectangle
					})
				} else {
					const errorMsg = response.data.info || '获取位置信息失败'
					console.warn('位置信息获取失败:', errorMsg)
					uni.showToast({
						title: errorMsg,
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('网络请求异常:', error)
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
			} finally {
				this.isLoading = false
			}
		}
	}
}
</script>

<style>
.content {
	padding: 20px;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.input-area {
	display: flex;
	gap: 10px;
	margin-bottom: 20px;
	background-color: #fff;
	padding: 15px;
	border-radius: 12px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.ip-input {
	flex: 1;
	height: 40px;
	padding: 0 15px;
	border: 1px solid #e4e7ed;
	border-radius: 8px;
	font-size: 14px;
	transition: all 0.3s ease;
}

.ip-input:focus {
	border-color: #007AFF;
	box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
}

.search-btn {
	width: auto;
	height: 40px;
	line-height: 40px;
	padding: 0 25px;
	background-color: #007AFF;
	color: #fff;
	border-radius: 8px;
	font-size: 14px;
	font-weight: 500;
	transition: all 0.3s ease;
}

.search-btn:active {
	transform: scale(0.98);
	background-color: #0062cc;
}

.result-area {
	background-color: #fff;
	padding: 20px;
	border-radius: 12px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.info-item {
	display: flex;
	margin-bottom: 15px;
	padding: 12px;
	border-radius: 8px;
	transition: background-color 0.3s ease;
}

.info-item:hover {
	background-color: #f5f7fa;
}

.info-item:last-child {
	margin-bottom: 0;
}

.label {
	color: #606266;
	width: 120px;
	font-size: 14px;
	font-weight: 500;
}

.value {
	color: #303133;
	flex: 1;
	font-size: 14px;
}

.copyright-area {
	margin-top: 30px;
	padding: 0 20px;
}

.copyright-card {
	background-color: #fff;
	border-radius: 12px;
	padding: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.copyright-item {
	display: flex;
	margin-bottom: 12px;
}

.copyright-item:last-child {
	margin-bottom: 0;
}

.copyright-label {
	color: #666;
	width: 80px;
	font-size: 14px;
}

.copyright-value {
	color: #333;
	flex: 1;
	font-size: 14px;
}
.system-info {
	background-color: #f0f7ff;
	padding: 20px;
	border-radius: 12px;
	box-shadow: 0 2px 8px rgba(0, 122, 255, 0.1);
	margin-bottom: 20px;
}

.history-toggle {
	background-color: #fff;
	padding: 15px;
	border-radius: 12px;
	margin-bottom: 15px;
	cursor: pointer;
	transition: all 0.3s ease;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-toggle:hover {
	background-color: #f5f7fa;
}

.toggle-icon {
	color: #007AFF;
	font-size: 16px;
	transition: transform 0.3s ease;
}

.history-list {
	background-color: #fff;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	margin-bottom: 20px;
}

.history-item {
	padding: 15px;
	border-bottom: 1px solid #f0f0f0;
	transition: all 0.3s ease;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.history-item:last-child {
	border-bottom: none;
}

.history-item:hover {
	background-color: #f5f7fa;
}

.history-ip {
	color: #007AFF;
	font-weight: 500;
	font-size: 14px;
}

.history-location {
	color: #606266;
	font-size: 14px;
}
.info-item:last-child {
	margin-bottom: 0;
}

.label {
	color: #606266;
	width: 120px;
	font-size: 14px;
	font-weight: 500;
}

.value {
	color: #303133;
	flex: 1;
	font-size: 14px;
}

.copyright-area {
	margin-top: 30px;
	padding: 0 20px;
}

.copyright-card {
	background-color: #fff;
	border-radius: 12px;
	padding: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.copyright-item {
	display: flex;
	margin-bottom: 12px;
}

.copyright-item:last-child {
	margin-bottom: 0;
}

.copyright-label {
	color: #666;
	width: 80px;
	font-size: 14px;
}

.copyright-value {
	color: #333;
	flex: 1;
	font-size: 14px;
}
</style>
